package org.osm.video;

import org.osm.jsoup.Jsoup;
import org.osm.jsoup.nodes.Document;
import org.osm.jsoup.nodes.Element;
import org.osm.jsoup.select.Elements;

import com.yingyi.mtw.base.util.Open56Client;
import com.yingyi.mtw.base.util.Open56VideoInfo;
import com.yingyi.mtw.base.util.Open56VideoWapper;

/**
 * 视频网址视频信息提取工具类
 * 支持以下网址：优酷、土豆、酷6、6间房、新浪、搜狐、56(我乐)、凤凰视频
 * 版本更新说明：
 * 1、2011-09-12 创建
 * 2、2011-09-13 新加对凤凰视频的支持，链接地址不在支持的列表中时返回原链接地址以及链接的页面标题
 * @author Guihua Liu
 * @version v1.0
 * @QQ 459041012
 * @email 850823422@139.com
 * @Website http://liuguihua.com
 */
public class VideoUtil {

	/**
	 * 获取视频信息
	 * 
	 * @param url
	 * @return
	 * @throws Exception 
	 */
	public static Video getVideoInfo(String url) throws Exception {
		Video video = null;
		
		if (url.indexOf(Constants.VIDEO_DOMAIN_YOUKU) != -1) {
			try {
				
				video = getYouKuVideo(url);
				System.out.println(video.getTitle());
			} catch (Exception e) {
				video = null;
			}
		} else if (url.indexOf(Constants.VIDEO_DOMAIN_TUDOU) != -1) {
			try {
				video = getTudouVideo(url);
			} catch (Exception e) {
				video = null;
			}
		} else if (url.indexOf(Constants.VIDEO_DOMAIN_KU6) != -1) {
			try {
				video = getKu6Video(url);
			} catch (Exception e) {
				video = null;
			}
		} else if (url.indexOf(Constants.VIDEO_DOMAIN_CN6) != -1) {
			try {
				video = get6Video(url);
			} catch (Exception e) {
				video = null;
			}
		} else if (url.indexOf(Constants.VIDEO_DOMAIN_WOLE) != -1) {
			try {
				video = get56Video(url);
			} catch (Exception e) {
				video = null;
			}
		} else if (url.indexOf(Constants.VIDEO_DOMAIN_SINA) != -1) {
			try {
				video = getSinaVideo(url);
			} catch (Exception e) {
				video = null;
			}
		} else if (url.indexOf(Constants.VIDEO_DOMAIN_SOHU) != -1) {
			try {
				video = getSohuVideo(url);
			} catch (Exception e) {
				video = null;
			}
		} else if (url.indexOf(Constants.VIDEO_DOMAIN_IFENG) != -1) {
			try {
				video = getIfengVideo(url);
			} catch (Exception e) {
				video = null;
			}
		} else if (url.indexOf(Constants.VIDEO_DOMAIN_YINYUETAI) != -1) {
			try {
				video = getYinYueTaiVideo(url);
			} catch (Exception e) {
				video = null;
			}
		} else {
			//链接地址不在支持的列表中时返回原链接地址以及链接的页面标题
			Document doc = getURLContent(url);
			video = new Video();
			video.setTitle(doc.title());
			video.setPageUrl(url);
		}

		return video;
	}

	/**
	 * 获取优酷视频
	 * 
	 * @param url 视频URL
	 */
	public static Video getYouKuVideo(String url){
		
		
		

		/**
		 * 获取视频缩略图
		 */
		
		try {
			Document doc = getURLContent(url);
			
			/**
			 * 视频标题
			 */
			String title = doc.title().split("-")[0].trim();
		String	pic = getElementAttrById(doc, "s_sina", "href");
			int local = pic.indexOf("pic=");
			pic = pic.substring(local + 4);
			
			/**
			 * 获取视频地址
			 */
			String flash = getElementAttrById(doc, "link2", "value");
			
			/**
			 * 获取视频网页代码
			 */
			String htmlCode = getElementAttrById(doc, "link3", "value");
			
			/**
			 * 获取视频时间
			 
			String time = getElementAttrById(doc, "download", "_href");
			String[] arrays = time.split("\\|");
			time = arrays[4];
			*/
			/**
			 * 获取视频简介
			 
			Element el =  doc.getElementById("long");
			String summary = el.select(".item").get(0).html();
			*/
			Video video = new Video();
			video.setTitle(title);
			video.setThumbnail(pic);
			video.setFlashUrl(flash);
			//video.setTime(time);
			video.setSource("优酷视频");
			video.setPageUrl(url);
			//video.setSummary(summary);
			video.setHtmlCode(htmlCode);
		

			return video;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
	}

	/**
	 * 获取土豆视频
	 * 
	 * @param url 视频URL
	 */
	public static Video getTudouVideo(String url) {
		url = url.trim();
		String[] urls = url.split("/");
		String tudou_id = null;
		
		if(urls.length > 0){
			if(urls[urls.length-1].indexOf(".html") > -1){
				tudou_id = urls[urls.length-1].substring(0,urls[urls.length-1].indexOf(".")); 
			}else{
				tudou_id = urls[urls.length-2];
			}
		}else{
			return null;
		}
		
		String api ="http://api.tudou.com/v5/item.info.get/3/4f3b29d5c0a80001c0a80001000000000662beb701/xml/?itemCodes="+tudou_id+"&param2=abcdefg&param1=abcdefg";
		try{
		Document doc = getURLContent(api);
		
		/**
		 * 视频标题
		 */
		String title = doc.select("title").html();

		/**
		 * 获取视频地址
		 */
		String flash = doc.select("outerplayerurl").html();

		/**
		 * 获取视频缩略图
		 */
		String pic = doc.select("bigpicurl").html();
		
		/**
		 * 视频简介
		 */
		String summary = doc.select("description").html();

		/**
		 * 获取视频时间
		 */
		String time = null;
		
		

		Video video = new Video();
		video.setTitle(title);
		video.setThumbnail(pic);
		video.setFlashUrl(flash);
		video.setTime(time);
		video.setSource("土豆视频");
		video.setPageUrl(url);
		video.setSummary(summary);
		video.setHtmlCode(getHtmlCode(flash));

		return video;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取酷6视频
	 * 
	 * @param url 视频URL
	 * @throws Exception 
	 */
	public static Video getKu6Video(String url)  {
		Document doc;
		try {
			doc = getURLContent("http://v.ku6.com/repaste.htm?url="+url);
		
			
			/**
			 * 获取视频标题
			 */
			String title = doc.select("title").text();


			/**
			 * 获取视频地址
			 */
			String flash = doc.select("flash").html();
			
			/**
			 * 获取视频地址
			 */
			String htmlCode =null;

			/**
			 * 获取视频缩略图
			 */
			
			String time = null;
			String pic = doc.select("coverurl").html();
		
			
			/**
			 * 视频简介
			 */
			String summary = doc.select("desc").html();


			Video video = new Video();
			video.setTitle(title);
			video.setThumbnail(pic);
			video.setFlashUrl(flash);
			video.setTime(time);
			video.setSource("酷6视频");
			video.setPageUrl(url);
			video.setSummary(summary);
			video.setHtmlCode(htmlCode);
			return video;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		

	}

	/**
	 * 获取6间房视频
	 * 
	 * @param url 视频URL
	 */
	public static Video get6Video(String url) throws Exception {
		Document doc = getURLContent(url);
		
		/**
		 * 视频标题
		 */
		String title = doc.title().split("-")[0].trim();

		/**
		 * 获取视频缩略图
		 */
		Element picEt = doc.getElementsByClass("summary").first();
		String pic = picEt.getElementsByTag("img").first().attr("src");

		
		/**
		 * 视频简介
		 */
		String summary = doc.select("meta[name=Description]").attr("content");

		/**
		 * 获取视频地址
		 */
		Element flashEt = doc.getElementById("video-share-code");
		doc = Jsoup.parse(flashEt.attr("value"));
		String flash = doc.select("embed").attr("src");

		Video video = new Video();
		video.setTitle(title);
		video.setThumbnail(pic);
		video.setFlashUrl(flash);
		video.setSource("6间房");
		video.setPageUrl(url);
		video.setSummary(summary);
		video.setHtmlCode(getHtmlCode(flash));

		return video;
	}

	/**
	 * 获取56视频
	 * 
	 * @param url 视频URL
	 */
	public static Video get56Video(String url) throws Exception {
		
		/**
		 * url:
		 * http://www.56.com/u60/v_NzAxNDk1MTM.html
		 * http://www.56.com/w98/play_album-aid-9949753_vid-NzExNjg3OTM.html
		 */
		String vid = null;
		String[] urls= url.split("/");
		if(urls[urls.length-1].indexOf("vid-") > -1){
			vid = urls[urls.length-1].substring(urls[urls.length-1].lastIndexOf("-")+1,urls[urls.length-1].indexOf(".html"));
		}else{
			vid = urls[urls.length-1].substring(urls[urls.length-1].lastIndexOf("_")+1,urls[urls.length-1].indexOf(".html"));
		}
		System.out.println(vid);
		Open56Client op56 = new Open56Client("1000000010","0e4f13954bc537ec");
		String content =op56.getVideoInfoApp(vid);
		Open56VideoWapper opW = Open56VideoInfo.InfoWapper(content);
		Open56VideoInfo info = opW.getOpInfo();
		
		Document doc = getURLContent(url);
		 content = doc.html();
		
		/**
		 * 视频标题
		 */
		String title = info.getTitle();

		/**
		 * 获取视频缩略图
		 */
	
		String pic = info.getBimg();

		/**
		 * 获取视频地址
		 */
		String flash = info.getSwf();
		
		/**
		 * 视频简介
		 */
		String summary = info.getDesc();
		Video video = new Video();
		video.setTitle(title);
		video.setThumbnail(pic);
		video.setFlashUrl(flash);
		video.setSource("56视频");
		video.setPageUrl(url);
		video.setSummary(summary);
		video.setHtmlCode(getHtmlCode(flash));
		return video;
	}
	
	/**
	 * 获取新浪视频
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Video getSinaVideo(String url) throws Exception {
		Document doc = getURLContent(url);
		
		/**
		 * 视频标题
		 */
		String title = doc.getElementById("videoTitle").text();
		
		/**
		 * 视频简介
		 */
		String summary = doc.getElementById("videoContent").text();
		
		String content = doc.html();
		int beginLocal = content.indexOf("document.domain");
		int endLocal = content.indexOf("</script>");
		content = content.substring(beginLocal+2, endLocal);
		
		/**
		 * 视频缩略图
		 */
		String pic = getScriptVarByName("pic", content);
		
		/**
		 * flash地址
		 */
		String flash = getScriptVarByName("swfOutsideUrl", content);
		
		Video video = new Video();
		video.setTitle(title);
		video.setThumbnail(pic);
		video.setFlashUrl(flash);
		video.setSource("新浪视频");
		video.setPageUrl(url);
		video.setSummary(summary);
		video.setHtmlCode(getHtmlCode(flash));
		return video;
	}
	
	/**
	 * 获取搜狐视频
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Video getSohuVideo(String url) throws Exception {
		Document doc = getURLContent(url);
		
		/**
		 * 视频标题
		 */
		String title = doc.title().split("-")[0].trim();
		
		/**
		 * 视频简介
		 */
		String summary = doc.select(".vIntro.clear > p").text();
		
		/**
		 * 视频缩略图
		 */
		String thumbnail = doc.getElementById("thumbnail").attr("src");
		
		String videoId = thumbnail.split("_")[2];
		
		/**
		 * 视频FLASH地址
		 */
		String flash = "http://share.vrs.sohu.com/"+videoId+"/v.swf&autoplay=false";
		
		Video video = new Video();
		video.setTitle(title);
		video.setThumbnail(thumbnail);
		video.setFlashUrl(flash);
		video.setSource("搜狐视频");
		video.setPageUrl(url);
		video.setSummary(summary);
		video.setHtmlCode(getHtmlCode(flash));
		return video;
	}
	
	/**
	 * 获取凤凰视频
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Video getIfengVideo(String url) throws Exception {
		Document doc = getURLContent(url);
		String content = doc.html();
		int beginLocal = content.indexOf("videoinfo={");
		int endLocal = content.indexOf("</script>");
		content = content.substring(beginLocal, endLocal);
		content = content.replaceAll("\"", "").replaceAll("\n", "").trim();
		content = content.substring(11, content.length()-2);
		String[] params = content.split(",");
		
		/**
		 * 视频标题
		 */
		String title = doc.select(".playtitle > h1").text();
		
		/**
		 * 视频简介
		 */
		String summary = doc.getElementById("full_des").text();
		summary = summary.replaceAll("<<收起", "");
		
		/**
		 * 视频FLASH地址
		 */
		String videoId = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".shtml"));
		String flash = "http://v.ifeng.com/include/exterior.swf?guid="+videoId+"&AutoPlay=false";
		
		/**
		 * 视频缩略图
		 */
		String thumbnail = params[5].substring(4, params[5].length());
		
		/**
		 * 视频时长
		 */
		String time = params[3].substring(9, params[3].length());
		long ss = Long.parseLong(time);
		long hour=ss/3600;
	    long minute=ss%3600/60;
	    long second=ss%60;
		
		Video video = new Video();
		video.setTitle(title);
		video.setThumbnail(thumbnail);
		video.setFlashUrl(flash);
		video.setTime(hour+":"+minute+":"+second);
		video.setSource("凤凰视频");
		video.setPageUrl(url);
		video.setSummary(summary);
		video.setHtmlCode(getHtmlCode(flash));
		return video;
	}
	
	
	/**
	 * 获取音悦台MV
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static Video getYinYueTaiVideo(String url) throws Exception {
		Document doc = getURLContent(url);
		
		/**
		 * 获取视频地址
		 */
		String flash = getElementAttrById(doc, "flashCode", "value");
		
		/**
		 * 视频标题
		 */
		String title = doc.getElementById("videoTitle").html()+" - "+doc.getElementById("videoArtistName").html();

		/**
		 * 视频内容
		 */
		String summary = doc.getElementById("videoContent").select("span").first().html();
		
		/**
		 * 视频缩略图
		 */
		String thumbnail = doc.select("meta[property=og:image]").attr("content");
		
		Video video = new Video();
		video.setTitle(title);
		video.setThumbnail(thumbnail);
		video.setFlashUrl(flash);
		video.setSource("音悦台MV");
		video.setPageUrl(url);
		video.setSummary(summary);
		video.setHtmlCode(getHtmlCode(flash));
		return video;
	}
	/**
	 * 获取script某个变量的值
	 * 
	 * @param name 变量名称
	 * @return 返回获取的值
	 */
	private static String getScriptVarByName(String name, String content) {
		String script = content;
		int begin = script.indexOf(name);
		script = script.substring(begin + name.length() + 2);
		int end = script.indexOf(",");
		script = script.substring(0, end);
		String result = script.replaceAll("'", "");
		return result.trim();
	}

	/**
	 * 根据HTML的ID键及属于名，获取属于值
	 * 
	 * @param id HTML的ID键
	 * @param attrName 属于名
	 * @return 返回属性值
	 */
	private static String getElementAttrById(Document doc, String id, String attrName) throws Exception {
		Element et = doc.getElementById(id);
		String attrValue = et.attr(attrName);
		return attrValue;
	}
	
	/**
	 * 根据FLASH地址生成页面代码
	 * @param flashUrl
	 * @return
	 * @throws Exception
	 */
	private static String getHtmlCode(String flashUrl) throws Exception {
		return "<embed src=\""+flashUrl+"\" allowFullScreen=\"true\" quality=\"high\" width=\"480\" height=\"400\" align=\"middle\" allowScriptAccess=\"always\" type=\"application/x-shockwave-flash\"></embed>";
	}
	

	/**
	 * 获取网页的内容
	 */
	private static Document getURLContent(String url) throws Exception {
		Document doc = Jsoup.connect(url)
						.data("query", "Java")
						.userAgent("Mozilla")
						.cookie("auth", "token")
						.timeout(5000).get();
		return doc;
	}

}